package cn.iocoder.yudao.module.javainfo.service.user;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.javainfo.controller.admin.user.vo.UserPageReqVO;
import cn.iocoder.yudao.module.javainfo.controller.admin.user.vo.UserRespVO;
import cn.iocoder.yudao.module.javainfo.controller.admin.user.vo.UserSaveReqVO;
import cn.iocoder.yudao.module.javainfo.dal.dataobject.user.UserDO;
import cn.iocoder.yudao.module.javainfo.dal.mysql.pet.PetMapper;
import cn.iocoder.yudao.module.javainfo.dal.mysql.user.JavaInfoUserMapper;
import cn.iocoder.yudao.module.javainfo.events.UserCreatedEvent;
import cn.iocoder.yudao.module.javainfo.service.financialflow.FinancialFlowService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.javainfo.enums.ErrorCodeConstants.JAVA_USER_HAS_PETS;
import static cn.iocoder.yudao.module.javainfo.enums.ErrorCodeConstants.JAVA_USER_NOT_EXISTS;

/**
 * 用户 Service 实现类
 *
 * @author 爪哇国大BOSS
 */
@Service
@Validated
public class JavaInfoUserServiceImpl implements JavaInfoUserService {

    @Resource
    private JavaInfoUserMapper javaInfoUserMapper;

    @Resource
    private PetMapper petMapper;

    @Autowired
    private ApplicationEventPublisher applicationEventPublisher;

    @Resource
    @Lazy
    private FinancialFlowService financialFlowService;

    @Override
    @Transactional
    public Long createUser(UserSaveReqVO createReqVO) {
        // 插入
        UserDO user = BeanUtils.toBean(createReqVO, UserDO.class);
        javaInfoUserMapper.insert(user);
        // 发布用户创建事件
        applicationEventPublisher.publishEvent(new UserCreatedEvent(this, user));
        // 返回
        return user.getId();
    }

    @Override
    public void updateUser(UserSaveReqVO updateReqVO) {
        // 校验存在
        validateUserExists(updateReqVO.getId());
        // 更新
        UserDO updateObj = BeanUtils.toBean(updateReqVO, UserDO.class);
        javaInfoUserMapper.updateById(updateObj);
    }

    @Override
    public void deleteUser(Long id) {
        // 校验存在
        validateUserExists(id);

        // 校验用户名下是否有宠物信息
        validateUserHasNoPets(id);

        // 删除
        javaInfoUserMapper.deleteById(id);
    }

    /**
     * 校验用户名下是否有宠物信息
     *
     * @param userId 用户ID
     */
    private void validateUserHasNoPets(Long userId) {
        Long petCount = petMapper.selectCountByUserId(userId);
        if (petCount > 0) {
            throw exception(JAVA_USER_HAS_PETS);
        }
    }

    @Override
    public void deleteUserListByIds(List<Long> ids) {
        if (CollectionUtils.isEmpty(ids)) {
            return;
        }

        // 校验用户是否存在
        ids.forEach(this::validateUserExists);

        // 校验用户名下是否有宠物信息
        for (Long id : ids) {
            validateUserHasNoPets(id);
        }

        // 删除
        javaInfoUserMapper.deleteByIds(ids);
    }


    private void validateUserExists(Long id) {
        if (javaInfoUserMapper.selectById(id) == null) {
            throw exception(JAVA_USER_NOT_EXISTS);
        }
    }

    @Override
    public UserDO getUser(Long id) {
        return javaInfoUserMapper.selectById(id);
    }

    @Override
    public PageResult<UserRespVO> getUserPage(UserPageReqVO pageReqVO) {
        PageResult<UserDO> userDOPageResult = javaInfoUserMapper.selectPage(pageReqVO);
        PageResult<UserRespVO> pageResult = BeanUtils.toBean(userDOPageResult, UserRespVO.class);
        // 查询每个用户对应的余额
        List<Long> userIds = pageResult.getList().stream().map(UserRespVO::getId).collect(Collectors.toList());
        Map<Long, String> userBalanceMap = financialFlowService.getUserBalanceMap(userIds);
        // 合并数据
        pageResult.getList().forEach(user -> user.setBalance(userBalanceMap.get(user.getId())));
        return pageResult;
    }

    @Override
    public Map<Long, String> getUserMap(List<Long> userIds) {
        if (CollectionUtils.isEmpty(userIds)) {
            return Collections.emptyMap();
        }
        List<UserDO> list = javaInfoUserMapper.selectBatchIds(userIds);
        if (CollectionUtils.isEmpty(list)) {
            return Collections.emptyMap();
        }
        return list.stream().collect(Collectors.toMap(UserDO::getId, UserDO::getUserName));
    }

}